package com.alter.consumer.consumer;

import com.alter.consumer.entity.Order;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Created by hucong on 2019/6/9.
 */
@Component
public class OrderReceiver {

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "queue-1", durable = "true"),
            exchange = @Exchange(name="exchange-1", durable = "true", type="topic", ignoreDeclarationExceptions="true"),
            key = "springboot.*"
    ))
    @RabbitHandler
    public void onMessage(Message message, Channel channel) throws Exception{
        //消费者操作
        System.err.println("-----收到消息，开始消费-----");
        System.err.println("消费端：" + message.getPayload().toString());

        Long deliveyTag = (Long)message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
        //手工ACK
        channel.basicAck(deliveyTag,false);
    }



    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "${spring.rabbitmq.listener.order.queue.name}",
                    durable = "${spring.rabbitmq.listener.order.queue.durable}"),
            exchange = @Exchange(name="${spring.rabbitmq.listener.order.exchange.name}",
                    durable = "${spring.rabbitmq.listener.order.exchange.durable}",
                    type = "${spring.rabbitmq.listener.order.exchange.type}",
                    ignoreDeclarationExceptions = "${spring.rabbitmq.listener.order.exchange.ignoreDeclarationExceptions}"
            ),
            key = "${spring.rabbitmq.listener.order.key}"
    ))
    @RabbitHandler
    public void onOrderMessage(@Payload Order order,
                               @Header Map<String, Object> headers,
                               Channel channel) throws Exception{
        //消费者操作
        System.err.println("-----收到消息，开始消费-----");
        System.err.println("订单ID：" + order.getId());

        Long deliveyTag = (Long)headers.get(AmqpHeaders.DELIVERY_TAG);
        //ACK
        channel.basicAck(deliveyTag,false);
    }
}
